import json

from django.views.decorators.csrf import csrf_exempt

from accounts_sys.models import *
from utils.response_utils import *
from utils.session_utils import *
from utils.string_utils import *
from utils.type_utils import *


@csrf_exempt
def register(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if has_login(request):
        user = User.objects.get(id=get_login_id(request))
        return login_status_response({
            "user": user.parse_dict()
        }, actual_login_status=True)

    data = json.loads(request.body)
    user_name = data.get('user_name')
    email = data.get('email')
    password = data.get('password')

    if contains_none(user_name, email, password):  # 不存在该键
        return format_error_response()

    if contains_false_val(user_name, email, password):  # 为空串
        return build_response(errno=2001, msg="user_name, email, password均不能为空")

    if not (2 <= len(user_name) <= 31) or valid_email(user_name):  # 不可以使用邮箱格式的用户名
        return build_response(errno=2002, msg="用户名不合法")

    if not (6 <= len(email) <= 63) or not valid_email(email):
        return build_response(errno=2003, msg="邮箱不合法")

    if not (4 <= len(password) <= 31):
        return build_response(errno=2004, msg="密码不合法")

    if User.objects.filter(user_name=user_name).exists():
        return build_response(errno=2005, msg="用户名已存在")

    if User.objects.filter(email=email).exists():
        return build_response(errno=2006, msg="邮箱已存在")

    User.objects.create(user_name=user_name, email=email, password=password)
    return build_response(msg="注册成功")


@csrf_exempt
def login(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if has_login(request):
        user = User.objects.get(id=get_login_id(request))
        return login_status_response({
            "user": user.parse_dict()
        }, actual_login_status=True)

    data = json.loads(request.body)
    account = data.get('account')
    password = data.get('password')

    if contains_none(account, password):  # 不存在该键
        return format_error_response()

    if contains_false_val(account, password):  # 为空串
        return build_response(errno=2001, msg="account, password均不能为空")

    # 获取user对象和登录方式（user_name或email），获取失败则user置为None
    cur_login_method = "email" if valid_email(account) else "user_name"
    try:
        user = User.objects.get(**{cur_login_method: account})
    except User.DoesNotExist:
        user = None

    if user is None:
        return build_response(errno=2002, msg="账户不存在")

    if password != user.password:
        return build_response({
            "login_method": cur_login_method
        }, errno=2003, msg="密码错误")

    set_login_id(request, user.id)
    return build_response({
        "login_method": cur_login_method,
        "user": user.parse_dict()
    }, msg="登录成功")


@csrf_exempt
def logout(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    del_login_id(request)
    return build_response(msg="登出成功")


@csrf_exempt
def get_current_user(request):
    if request.method not in ['POST', 'GET']:
        return method_disallowed_response(request.method, 'POST', 'GET')

    if not has_login(request):
        return login_status_response()

    user_id = get_login_id(request)
    assert user_id  # 确保user_id不为None
    user = User.objects.get(id=user_id)

    return build_response({
        "user": user.parse_dict()
    }, msg="获取成功")


@csrf_exempt
def modify_account_info(request, field):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    user = get_login_user(request)
    data = json.loads(request.body)

    if field == 'user_name':
        new_user_name = data.get('new_user_name')
        if new_user_name is None:
            return format_error_response()
        if not (2 <= len(new_user_name) <= 31) or valid_email(new_user_name):
            return build_response(errno=2001, msg="用户名不合法")
        if user.user_name == new_user_name:
            return build_response({
                "user": user.parse_dict()
            }, msg="用户名未发生变化")
        if User.objects.filter(user_name=new_user_name).exists():
            return build_response(errno=2002, msg="用户名已存在")
        User.objects.filter(id=user.id).update(user_name=new_user_name)
        return build_response({
            "user": user.parse_dict()
        }, msg="修改成功")

    elif field == 'email':
        new_email = data.get('new_email')
        if new_email is None:
            return format_error_response()
        if not (6 <= len(new_email) <= 63) or not valid_email(new_email):
            return build_response(errno=2001, msg="邮箱不合法")
        if user.email == new_email:
            return build_response({
                "user": user.parse_dict()
            }, msg="邮箱未发生变化")
        if User.objects.filter(email=new_email).exists():
            return build_response(errno=2002, msg="邮箱已存在")
        User.objects.filter(id=user.id).update(email=new_email)
        return build_response({
            "user": user.parse_dict()
        }, msg="修改成功")

    elif field == 'password':
        origin_password = data.get('origin_password')
        new_password = data.get('new_password')
        if new_password is None:
            return format_error_response()
        if origin_password != user.password:
            return build_response(errno=2001, msg="原密码错误")
        if not (4 <= len(new_password) <= 31):
            return build_response(errno=2002, msg="密码不合法")
        User.objects.filter(id=user.id).update(password=new_password)
        return build_response({
            "user": user.parse_dict()
        }, msg="修改成功")


